﻿using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFrameworkCore;
using Castle.MicroKernel.Registration;
using NetCore.EntityFrameworkCore.Repositories;
using NetCore.EntityFrameworkCore.Seed;
using NetCore.Interfaces;

namespace NetCore.EntityFrameworkCore
{
    [DependsOn(
        typeof(NetCoreCoreModule),
        typeof(AbpZeroCoreEntityFrameworkCoreModule))]
    public class NetCoreEntityFrameworkModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }

        public override void PreInitialize()
        {
            if (!SkipDbContextRegistration)
            {
                Configuration.Modules.AbpEfCore().AddDbContext<NetCoreDbContext>(options =>
                {
                    if (options.ExistingConnection != null)
                    {
                        NetCoreDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                    }
                    else
                    {
                        NetCoreDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                    }
                });
            }
        }

        public override void Initialize()
        {
            #region 查看源码发现abp新版本默认没有依赖注入泛型接口，需要手动注册
            //建议使用在Dbcontext上添加AutoRepositoryTypes 属性 
            //但测试AutoRepositoryTypes属性添加后运行错误,估计是版本或者泛型类的int和long的问题,目前使用手动注测

            IocManager.IocContainer.Register(Component.For(typeof(INetCoreRepository<>))
                .ImplementedBy(typeof(NetCoreRepositoryBase<>)).LifestyleTransient());
            IocManager.IocContainer.Register(Component.For(typeof(INetCoreRepository<,>))
                .ImplementedBy(typeof(NetCoreRepositoryBase<,>)).LifestyleTransient());

            //IocManager.IocContainer.Register(
            //    Classes.FromAssembly(typeof(NetCoreEntityFrameworkModule).GetAssembly())//这种方式注入有bug
            //        //.IncludeNonPublicTypes()
            //        .BasedOn<IRepository>()
            //        //.If(type => type.GetTypeInfo().Namespace == typeof(INetCoreRepository<>).GetTypeInfo().Namespace
            //        //            || type.GetTypeInfo().Namespace == typeof(INetCoreRepository<,>).GetTypeInfo().Namespace)
            //        .WithService.Self()
            //        .WithService.DefaultInterfaces()
            //        .LifestyleTransient()
            //);
            #endregion
            IocManager.RegisterAssemblyByConvention(typeof(NetCoreEntityFrameworkModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }
        }
    }
}
